package com.freestyle.jms.common;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URL;

@Component
public class EhcacheUtil {
  @Resource
  private CacheManager manager;

  public EhcacheUtil() {
  }

  private EhcacheUtil(String pvsConfigPath) {
    URL url = getClass().getResource(pvsConfigPath);
    manager = CacheManager.create(url);
  }

  public void put(String cacheName, String key, Object value,int timesSecondsForLive) {
      Cache cache=manager.getCache(cacheName);
      Element element = new Element(key, value,timesSecondsForLive,timesSecondsForLive);
      cache.put(element);
  }
  public void put(String cacheName, String key, Object value) {
    Cache cache = manager.getCache(cacheName);
    Element element = new Element(key, value);
    cache.put(element);
  }

  public <T> T get(String cacheName, String key) {
    Cache cache = manager.getCache(cacheName);
    Element element = cache.get(key);
    return element == null ? null : (T) element.getObjectValue();
  }

  public Cache get(String cacheName) {
    return manager.getCache(cacheName);
  }

  public void remove(String cacheName, String key) {
    Cache cache = manager.getCache(cacheName);
    cache.remove(key);
   }

}
